// src/renderer/workbench/template.js
// 模版管理模块 - 完整功能版 (基于 LocalStorage)

// 1. 系统预置模版 (只读，用于兜底)
const SYSTEM_TEMPLATES = {
  'sys_bank_default': {
    id: 'sys_bank_default',
    name: '银行流水通用模板',
    dataType: 'bank',
    isSystem: true,
    mappings: {
      '交易时间': 'transaction_time',
      '交易日期': 'transaction_time',
      '发生时间': 'transaction_time',
      '本方账号': 'account_number',
      '账号': 'account_number',
      '卡号': 'account_number',
      '交易金额': 'transaction_amount',
      '发生额': 'transaction_amount',
      '金额': 'transaction_amount',
      '借贷标志': 'debit_credit_flag',
      '对方户名': 'counterparty_name',
      '对方姓名': 'counterparty_name',
      '对方账号': 'counterparty_account',
      '对方卡号': 'counterparty_account',
      '摘要': 'remarks',
      '备注': 'remarks',
      '余额': 'balance_after'
    }
  },
  'sys_call_default': {
    id: 'sys_call_default',
    name: '话单通用模板',
    dataType: 'call',
    isSystem: true,
    mappings: {
      '机主姓名': 'user_name',
      '本机号码': 'user_number',
      '主叫号码': 'user_number',
      '对方号码': 'opp_user_number',
      '被叫号码': 'opp_user_number',
      '通话时间': 'start_time',
      '起始时间': 'start_time',
      '通话时长': 'duration',
      '时长': 'duration',
      '呼叫类型': 'call_type',
      '主被叫': 'call_type',
      '通话地点': 'location'
    }
  }
};

// 初始化
function initializeTemplateModule() {
  console.log('模版管理模块就绪');
}

// 获取所有模板 (系统 + 用户)
function getAllTemplates() {
  let userTemplates = {};
  try {
    const stored = localStorage.getItem('fieldTemplates');
    if (stored) {
      userTemplates = JSON.parse(stored);
    }
  } catch (e) {
    console.error('读取本地模板失败', e);
  }
  return { ...SYSTEM_TEMPLATES, ...userTemplates };
}

// 保存用户模板
function saveUserTemplate(name, dataType, mappings) {
  try {
    const templates = JSON.parse(localStorage.getItem('fieldTemplates') || '{}');
    const id = `user_tpl_${Date.now()}`;

    templates[id] = {
      id,
      name,
      dataType,
      mappings,
      isSystem: false,
      createTime: new Date().toISOString()
    };

    localStorage.setItem('fieldTemplates', JSON.stringify(templates));
    return true;
  } catch (e) {
    console.error('保存模板失败', e);
    return false;
  }
}

// 删除用户模板
function deleteUserTemplate(id) {
  try {
    if (SYSTEM_TEMPLATES[id]) {
      alert('系统内置模板无法删除');
      return false;
    }
    const templates = JSON.parse(localStorage.getItem('fieldTemplates') || '{}');
    if (templates[id]) {
      delete templates[id];
      localStorage.setItem('fieldTemplates', JSON.stringify(templates));
      return true;
    }
  } catch (e) {
    console.error('删除模板失败', e);
  }
  return false;
}

// --- 核心算法：自动匹配 ---
async function tryAutoMapFromTemplate(dataType, headers) {
  const allTemplates = Object.values(getAllTemplates());

  const candidates = allTemplates.filter(t => t.dataType === dataType);
  if (candidates.length === 0) return null;

  let bestTemplate = null;
  let maxMatchCount = 0;

  const normalizedHeaders = headers.map(h => String(h).trim().toLowerCase());

  for (const tpl of candidates) {
    let matchCount = 0;
    const mappings = tpl.mappings || {};

    for (const sourceField of Object.keys(mappings)) {
      const normSource = sourceField.trim().toLowerCase();
      if (normalizedHeaders.includes(normSource) || normalizedHeaders.some(h => h.includes(normSource))) {
        matchCount++;
      }
    }

    if (matchCount > maxMatchCount) {
      maxMatchCount = matchCount;
      bestTemplate = tpl;
    }
  }

  if (bestTemplate && maxMatchCount >= 2) {
    return bestTemplate;
  }

  return null;
}

// --- UI 部分：模版管理中心 ---

let currentCategory = 'bank';

function openTemplateManagementTab() {
  const tabId = 'template-manager';

  const sidebarHtml = window.SidebarModule.createSidebarHtml(
    currentCategory,
    'window.TemplateManager.switchCategory',
    '模版分类',
    null,
    'light'
  );

  const content = `
    <div class="template-manager-container" style="display:flex; height:100%; width:100%; background-color:#f5f7fa;">
      <div id="tpl-sidebar" style="height:100%;">
        ${sidebarHtml}
      </div>

      <main style="flex:1; display:flex; flex-direction:column; overflow:hidden;">
        <div style="padding:15px 20px; background:white; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center;">
          <h3 style="margin:0; color:#333;">模版管理</h3>
          <button class="btn-secondary" onclick="window.TemplateManager.refreshList()">刷新列表</button>
        </div>
        
        <div id="template-list-container" style="flex:1; padding:20px; overflow-y:auto;">
        </div>
      </main>
    </div>
  `;

  if (window.createTabInWorkbench) {
    window.createTabInWorkbench(tabId, '模版管理', content);
    renderTemplateList();
  }
}

function switchCategory(type) {
  currentCategory = type;
  const container = document.getElementById('tpl-sidebar');
  if (container) window.SidebarModule.updateSelection(container, type, 'light');
  renderTemplateList();
}

function renderTemplateList() {
  const container = document.getElementById('template-list-container');
  if (!container) return;

  const all = getAllTemplates();
  const list = Object.values(all).filter(t => t.dataType === currentCategory);

  if (list.length === 0) {
    container.innerHTML = `<div style="text-align:center; padding:50px; color:#999;">暂无【${window.DataModule.getDataTypeName(currentCategory)}】类型的模版</div>`;
    return;
  }

  let html = `<div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap:20px;">`;

  list.forEach(tpl => {
    const isSys = tpl.isSystem;
    const fieldCount = Object.keys(tpl.mappings).length;
    const badge = isSys ? `<span style="background:#e6f7ff; color:#1890ff; padding:2px 6px; font-size:12px; border-radius:4px;">系统预置</span>` : `<span style="background:#f6ffed; color:#52c41a; padding:2px 6px; font-size:12px; border-radius:4px;">用户自定义</span>`;

    html += `
      <div style="background:white; border:1px solid #ebeef5; border-radius:6px; padding:15px; box-shadow:0 2px 8px rgba(0,0,0,0.02); position:relative;">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
          <strong style="font-size:16px; color:#333;">${tpl.name}</strong>
          ${badge}
        </div>
        <div style="font-size:13px; color:#666; margin-bottom:5px;">包含字段数: <b>${fieldCount}</b></div>
        <div style="font-size:12px; color:#999; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
          示例: ${Object.keys(tpl.mappings).slice(0, 3).join(', ')}...
        </div>
        ${!isSys ? `
          <div style="margin-top:15px; text-align:right;">
             <button class="btn-secondary" style="padding:4px 10px; font-size:12px; color:#ff4d4f; border-color:#ffccc7;" onclick="window.TemplateManager.remove('${tpl.id}')">删除模版</button>
          </div>
        ` : ''}
      </div>
    `;
  });

  html += `</div>`;
  container.innerHTML = html;
}

function remove(id) {
  if (confirm('确定要删除这个模版吗？')) {
    if (deleteUserTemplate(id)) {
      renderTemplateList();
    }
  }
}

// 暴露全局
window.TemplateManager = {
  initializeTemplateModule,
  openTemplateManagementTab,
  getAllTemplates,
  saveUserTemplate,
  tryAutoMapFromTemplate,
  switchCategory,
  refreshList: renderTemplateList,
  remove
};